package com.third.clock.manager;

import android.content.Context;
import android.text.TextUtils;

import com.third.clock.bean.LoginEntity;
import com.third.clock.bean.ResponseData;
import com.third.clock.common.ConfigureLog4JUtil;
import com.third.clock.common.Contants;
import com.third.clock.common.MD5Utils;
import com.third.clock.common.SharedPreferencesUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.third.clock.common.Contants.ACTION_RTC_LOCATION;

/**
 * Created by Administrator on 2018/7/21 0021.
 */

public class ClockManager implements IBaseManager,IManagerEvent{

    private Context mContext;

    private TimerManager mTimerManager;

    private OkHttpClientManager okHttpClientManager;

    private LocationManager mLocationManager;

    private UmengManager mUmengManager;

    private NetWorkManager mNetWorkManager;

    private SharedPreferencesUtils mSharedPreferencesUtils;

    public ResponseData<LoginEntity> mLoginResponseData;

    public String loginSecret;

    private static ClockManager mClockManager;

    private ClockManager(Context context){
        this.mContext=context;
    }

    public static ClockManager getInstace(Context context){
        if(mClockManager==null){
            synchronized (ClockManager.class){
                if(mClockManager==null){
                    mClockManager=new ClockManager(context);
                }
            }
        }
        return mClockManager;
    }


    @Override
    public void onCreate() {
        mUmengManager=UmengManager.getInstance(mContext);

        ConfigureLog4JUtil.getInstall().configure();

        mSharedPreferencesUtils=SharedPreferencesUtils.getInstance(mContext);

        mTimerManager=new TimerManager(mContext,this);
        mTimerManager.onCreate();

        mLocationManager=new LocationManager(mContext);
        mLocationManager.onCreate();

        mNetWorkManager=new NetWorkManager(mContext);
        mNetWorkManager.onCreate();
        mNetWorkManager.registerOnNetWorkChaneObserve(networkobserve);

        okHttpClientManager=new OkHttpClientManager(mContext);
        okHttpClientManager.onCreate();


    }


    @Override
    public void onDestroy() {
        mTimerManager.onDestroy();
        okHttpClientManager.onDestroy();
        mLocationManager.onDestroy();
    }

    @Override
    public TimerManager getTimerManager() {
        return mTimerManager;
    }

    @Override
    public OkHttpClientManager getOkHttpClientManager() {
        return okHttpClientManager;
    }

    @Override
    public LocationManager getLocationManager() {
        return mLocationManager;
    }

    @Override
    public UmengManager getUmengManager() {
        return mUmengManager;
    }

    @Override
    public NetWorkManager getNetWorkManager() {
        return mNetWorkManager;
    }

    private NetWorkManager.OnNetWorkChaneObserve networkobserve=new NetWorkManager.OnNetWorkChaneObserve() {
        @Override
        public void onNetWorkChane(boolean isConnect) {
            if(isConnect){
                 //重新连接
                 login(null);
                 // 重新注册友盟
                 registPushAgent();
            }
            ConfigureLog4JUtil.getInstall().printLogger("NetWorkManager onNetWorkChane isConnect="+isConnect);
        }
    };

    public void login(final OkHttpClientManager.okHttpCallback callback){
        if(mSharedPreferencesUtils!=null) {
            String password = mSharedPreferencesUtils.getStringValue(SharedPreferencesUtils.PASSWORD_KEY,"");
            String username = mSharedPreferencesUtils.getStringValue(SharedPreferencesUtils.USERNAME_KTY,"");
            if(!TextUtils.isEmpty(password)&&!TextUtils.isEmpty(username)){
                loginSecret= MD5Utils.parseStrToMd5L32("mobile="+username+"&"+"password="+password+ Contants.MD5_SECRET);

                final Map<String, Object> params = new HashMap<>();
                params.put("mobile",username);
                params.put("password",password);
                params.put("sign",loginSecret);

                if(okHttpClientManager!=null){
                    okHttpClientManager.post(Contants.LOGIN_URL,params,new OkHttpClientManager.okHttpCallback(){
                        @Override
                        public void onFailure(com.lzy.okgo.model.Response<String> response) {
                            if(callback!=null) callback.onFailure(response);
                        }

                        @Override
                        public void onResponse(com.lzy.okgo.model.Response<String> response) {
                            if(callback!=null) callback.onResponse(response);
                            if(response!=null&&response.body()!=null){
                                try {
                                    mLoginResponseData = TransformManager.paserLogin(response.body());
                                    if (mLoginResponseData != null) {
                                        if (mLoginResponseData.getCode() == Contants.CODE_0) {
                                            //开启GPS定位
                                            mLocationManager.startLocation();
                                            getUploadInterval();
                                            //mTimerManager. startAlarm(mContext,Contants.ACTION_RTC_LOCATION,Contants.PENDINGINTENT_LOCATION,TimerManager.RTC_LOCATION);
                                        }
                                    }
                                }catch (Exception e){}
                            }
                        }
                    });
                }
            }
        }
    }

    public void registPushAgent(){
        if(mUmengManager!=null){
            if(TextUtils.isEmpty(mUmengManager.getDevicetoken())){
                mUmengManager.onCreate();
            }
        }
    }

    private void getUploadInterval(){
        Map<String,Object> uploadIntervalMap=new HashMap<>();
        String toSign=TransformManager.sortMapByKey(uploadIntervalMap);
        uploadIntervalMap.put("sign",toSign);
        if(okHttpClientManager!=null){
            okHttpClientManager.post(Contants.GETUPLOADINTERVAL_URL, uploadIntervalMap, new OkHttpClientManager.okHttpCallback() {
                @Override
                public void onFailure(com.lzy.okgo.model.Response<String> s) {
                    mTimerManager. startAlarm(mContext,Contants.ACTION_RTC_LOCATION,Contants.PENDINGINTENT_LOCATION,mTimerManager.RTC_LOCATION);
                }

                @Override
                public void onResponse(com.lzy.okgo.model.Response<String> response) {
                   if(response!=null&&response.body()!=null){
                       ResponseData<String> responseData=TransformManager.paserString(response.body());
                       if(responseData.getCode()==Contants.CODE_0&&responseData.getData()!=null){
                           long time=0;
                           try{
                               time=Long.parseLong(responseData.getData());
                           }catch (Exception e){

                           }
                           if(time!=0) {
                               mTimerManager.RTC_LOCATION=1000*time;
                           }
                       }
                       mTimerManager. startAlarm(mContext,Contants.ACTION_RTC_LOCATION,Contants.PENDINGINTENT_LOCATION,mTimerManager.RTC_LOCATION);
                   }else{
                       mTimerManager. startAlarm(mContext,Contants.ACTION_RTC_LOCATION,Contants.PENDINGINTENT_LOCATION,mTimerManager.RTC_LOCATION);
                   }
                }
            });
        }

    }


}
